﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Globalization;
using System.IO.Compression;
using System.Web.Mvc;

namespace CantinhodaCegonha.Models.Helpers
{
    public static class Util
    {
        public static string RemoveDiacritics(this string s)
        {
            string stFormD = s.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();

            for (int ich = 0; ich < stFormD.Length; ich++)
            {
                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
                if (uc != UnicodeCategory.NonSpacingMark)
                {
                    sb.Append(stFormD[ich]);
                }
            }
            return (sb.ToString().Normalize(NormalizationForm.FormC));
        }

        public static string GetDataPassada(DateTime LastUpdateDate)
        {
            TimeSpan elapsed = DateTime.Now.Subtract(LastUpdateDate);
            string LastUpdateDateFormated ="";

            if (elapsed.Days > 10)
                LastUpdateDateFormated = LastUpdateDate.ToShortDateString();
            else if (elapsed.Days > 0)
                LastUpdateDateFormated = elapsed.Days + " dias atrás";
            else if (elapsed.Hours > 0)
                LastUpdateDateFormated = elapsed.Hours + "h atrás";
            else if (elapsed.Minutes > 0)
                LastUpdateDateFormated = elapsed.Minutes + "m atrás";
            else if (elapsed.Seconds > 0)
                LastUpdateDateFormated = elapsed.Seconds + "s atrás";

            return LastUpdateDateFormated;
        }
    }

    public class CompressFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpResponseBase response = filterContext.HttpContext.Response;

            if (response.Filter is GZipStream || response.Filter is DeflateStream) return;

            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToLower();

            if (acceptEncoding.Contains("gzip"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("deflate"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }
}